package com.example.trackcircuitdiagnosis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.trackcircuitdiagnosis.entity.UserEntity;
import com.example.trackcircuitdiagnosis.exception.HttpResult;
import com.example.trackcircuitdiagnosis.exception.HttpResultGenerator;
import com.example.trackcircuitdiagnosis.mapper.UserMapper;
import com.example.trackcircuitdiagnosis.service.UserService;
import com.example.trackcircuitdiagnosis.utils.TokenUtil;
 import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    private static final String USER_ID_KET = "user_id_";
    private static final Integer USER_TTL = 24;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public HttpResult login(UserEntity user) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getUsername,user.getUsername());
        UserEntity userEntity = userMapper.selectOne(wrapper);
        if(userEntity != null){
            if (userEntity.getPassword().equals(user.getPassword())){
                //登录成功，生成用户token，以用户id为key向redis存入token
                String token = TokenUtil.getToken(userEntity.getId().toString());
                redisTemplate.opsForValue().set(USER_ID_KET+userEntity.getId().toString(),token,USER_TTL, TimeUnit.HOURS);
                return HttpResultGenerator.success(token);
            }
            else {
                return HttpResultGenerator.fail(503,"密码错误");

            }
        }
        else {
            return HttpResultGenerator.fail(504,"用户不存在");
        }


    }

    @Override
    public HttpResult logout(HttpServletRequest request) {
        String token = request.getHeader("x-access-token");
        String key = USER_ID_KET+ TokenUtil.parseToken(token);
        redisTemplate.opsForValue().getOperations().delete(key);
        return HttpResultGenerator.success("注销成功");
    }
}
